package com.ansion.commonchat.api;

import androidx.annotation.Keep;
import androidx.annotation.NonNull;

import com.ansion.CommonDataCallback;
import com.ansion.basedb.dao.helper.ContactsHelper;
import com.ansion.basedb.dao.helper.GroupHelper;
import com.ansion.basedb.dao.helper.UserHelper;
import com.ansion.basedb.dao.model.ContactsModel;
import com.ansion.basedb.dao.model.GroupModel;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.notify.UserChangeNotifier;
import com.ansion.basedb.util.UserModelNameUtils;
import com.ansion.basetool.preconditions.Preconditions;
import com.ansion.user.api.UserSdkApi;
import com.ansion.user.beanforui.ContactActiveInfo;
import com.ansion.user.beanforui.ContactInfo;
import com.ansion.user.listener.BaseContactChangeListener;
import com.ansion.user.listener.ContactActiveListener;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ThreadUtil;
import com.ansion.utils.ValueSafeTransfer;
import com.ansion.utils.thread.ThreadPool;

import java.util.ArrayList;
import java.util.List;


@Keep
public class UserSdkImpl implements UserSdkApi {
    @Override
    public void unregisterContactListener(BaseContactChangeListener contactChangeListener) {
        UserChangeNotifier.getInstance().removeListener(contactChangeListener);
    }

    @Override
    public void getContactInfo(@NonNull String uid, boolean showNickname, boolean useOriginalAvatar, @NonNull CommonDataCallback<ContactInfo> callback) {
        getContactInfo(uid, showNickname, useOriginalAvatar, false, callback);
    }

    private void getContactInfo(@NonNull String uid, boolean showNickname, boolean useOriginalAvatar, boolean queryGroupMember, @NonNull CommonDataCallback<ContactInfo> callback) {
        if (ThreadUtil.isUIThread()) {
            //优化线程使用
            if (ContactBuilder.needLoadFromDb(uid)) {//如果需要从db加载则开启子线程
                ThreadUtil.runOnWorker(() -> {
                    ContactInfo dbContact = ContactBuilder.getContactInfo(uid, showNickname, useOriginalAvatar, queryGroupMember);
                    callback.onSuccess(dbContact);
                });
            } else {//不需要从db加载则直接给回调，不用开子线程
                ContactInfo contactInfo = ContactBuilder.getContactInfo(uid, showNickname, useOriginalAvatar, queryGroupMember);
                callback.onSuccess(contactInfo);
            }
        } else {
            ContactInfo contactInfo = ContactBuilder.getContactInfo(uid, showNickname, useOriginalAvatar, queryGroupMember);
            callback.onSuccess(contactInfo);
        }
    }

    @Override
    public void getContactInfo(@NonNull String uid, boolean showNickname, @NonNull CommonDataCallback<ContactInfo> callback) {
        getContactInfo(uid, showNickname, false, callback);
    }

    @Override
    public void getContactInfo(@NonNull String uid, @NonNull CommonDataCallback<ContactInfo> callback) {
        getContactInfo(uid, false, callback);
    }

    @Override
    public void getContactInfoWithGroupMember(@NonNull String uid, @NonNull CommonDataCallback<ContactInfo> callback) {
        getContactInfo(uid, false, false, true, callback);
    }

    @Override
    public ContactInfo getContactInfo(@NonNull String uid) {
        return ContactBuilder.getContactInfo(uid, false, false);
    }


    @Override
    public void registerContactListener(BaseContactChangeListener contactChangeListener) {
        UserChangeNotifier.getInstance().addListener(contactChangeListener);
    }

    @Override
    public void getContactsInfo(@NonNull List<String> uidList, boolean showNickname, @NonNull CommonDataCallback<List<ContactInfo>> callback) {
        if (ThreadUtil.isUIThread()) {
            ThreadUtil.runDbTask(() -> {
                callback.onSuccess(loadContacts(uidList, showNickname));
            });
        } else {
            callback.onSuccess(loadContacts(uidList, showNickname));
        }
    }

    @Override
    public @NonNull List<ContactInfo> getContactsInfo(@NonNull List<String> uidList, boolean showNickname) {
        return loadContacts(uidList, showNickname);
    }

    private @NonNull  List<ContactInfo> loadContacts(@NonNull List<String> uidList, boolean showNickname) {
        List<ContactInfo> contactInfos = new ArrayList<>();
        for (String uid : uidList) {
            ContactInfo contactInfo = ContactBuilder.getContactInfo(uid, showNickname, false);
            contactInfos.add(contactInfo);
        }
        return contactInfos;
    }

    @Override
    public boolean isGroupMember(@NonNull String sessionId, @NonNull String uid) {
        Preconditions.checkNotEmpty(sessionId);
        Preconditions.checkNotEmpty(uid);
        GroupModel groupModel = GroupHelper.getGroupModel(sessionId);
        return groupModel != null && groupModel.isMember(uid);
    }

    @Override
    public void loadContactActiveInfo(@NonNull String uid, @NonNull CommonDataCallback<ContactActiveInfo> callback) {
        Preconditions.checkNotEmpty(uid);
        Preconditions.checkNotNull(callback);
        ThreadPool.runIO(new Runnable() {
            @Override
            public void run() {
//                UserActiveModel userActiveModel = LastSeenTimeManager.getLastSeenTimeModel(uid);
//                if (userActiveModel != null) {
//                    ContactActiveInfo contactActiveInfo = new ContactActiveInfo();
//                    contactActiveInfo.setActive(userActiveModel.isActive());
//                    contactActiveInfo.setTime(userActiveModel.getLastSeenTime());
//                    contactActiveInfo.setTimeString(TimeFormatUtil.getLastSeenTime(userActiveModel.isActive(), userActiveModel.getLastSeenTime()));
//                    callback.onSuccess(contactActiveInfo);
//                } else {
//                    callback.onFailure(-1, null);
//                }
            }
        });
    }

    @Override
    public void registerContactActiveListener(@NonNull ContactActiveListener listener) {
//        ContactActiveNotifier.getInstance().addListener(listener);
//        UserActiveHelper.getLastSeenTimeAndSubscribe(ValueSafeTransfer.longValue(listener.getUid()), true);
    }

    @Override
    public void unregisterContactActiveListener(@NonNull ContactActiveListener listener) {
//        UserActiveHelper.unsubscribeUserActive(ValueSafeTransfer.longValue(listener.getUid()));
//        ContactActiveNotifier.getInstance().removeListener(listener);
    }

    @Override
    public void getAllContactInfos(@NonNull CommonDataCallback<List<ContactInfo>> callback) {
        if (ThreadUtil.isUIThread()) {
            //优化线程使用
            ThreadPool.runDatabase(() -> {
                callback.onSuccess(innerAllContactInfos());
            });
        } else {
            callback.onSuccess(innerAllContactInfos());
        }
    }

    private List<ContactInfo> innerAllContactInfos() {
        List<ContactInfo> contactInfos = new ArrayList<>();
        List<ContactsModel> contactsModels = ContactsHelper.loadAll(true);
        if (contactsModels == null || contactsModels.size() == 0) {
            return contactInfos;
        }
        for (ContactsModel contactsModel : contactsModels) {
            if (contactsModel == null || contactsModel.getUserId() == 0L) {
                continue;
            }
            if (ContactUtil.isSelf(contactsModel.getUserId() + "")) {
                continue;
            }
            UserModel user = UserHelper.getUserModel(contactsModel.getUserId());
            if (user == null) {
                continue;
            }

            if (!UserModelNameUtils.isContactUser(user)) {
                continue;
            }
            ContactInfo contactInfo = ContactBuilder.buildContactInfo(user);
            contactInfos.add(contactInfo);
        }
        return contactInfos;
    }

    @Override
    public boolean verifyUser(String sessionId) {
        long uid = ValueSafeTransfer.longValue(sessionId);
        if (!ContactsHelper.isAppUser(uid)) { //过滤掉非好友
            return false;
        }
        if (ContactUtil.isSystemId(uid) && !ContactUtil.isFileAssistant(sessionId)) { //过滤掉系统帐号
            return false;
        }
        return true;
    }
}
